'''极端简单的模块,输入股票代码,获取历史分红与转送股信息,返回一个列表,
每一项为一个字典,{'date','xd','xr'},
date是股权登记日期(字符串),格式为'年-月-日',例如2019-2-13(个位的开头没有0);
'xd'与'xr'是每股(不是每10股)分红与转送股(合计)的数量,没有的话就是0.0了,浮点数格式.
列表顺序为时间顺序,访问的是新浪财经的资料.'''

import sys

import requests
from lxml import etree

## 传入代码,获取历史分红与转送股信息.如果获取信息失败,返回None
## 若isDebug = True,在文件夹中记录网页访问的响应文件
def GetStockBonus(code, isDebug = False):
  # 初始化返回列表,以及访问用链接
  result = []
  
  url = r'http://vip.stock.finance.sina.com.cn/corp/go.php/vISSUE_ShareBonus/stockid/{0}.phtml'.format(code)
  ## 访问并分析.成功则记录数据,失败返回None
  try:
    resp = requests.get(url)
    if(isDebug):
      with open(sys.path[0]+r'\html_test_result.txt','wb') as f:
        f.write(resp.content)
        print('Url content recorded!')
    tree = etree.HTML(resp.text)
    # 读取分红的相关table,tr
    table = tree.xpath('//table[@id="sharebonus_1"]')[0]
    trs = table.xpath('.//tbody//tr')
    if(isDebug):
      print('\nRead table OK,now prints all data:\n')
    # 读取tr中每一项的日期,分红,转送股信息,加入到列表中
    for i in range(len(trs)-1, -1 ,-1):
      # 新增的分红送股记录record
      record = {'date':None, 'xd':0.0, 'xr':0.0}
      record['date'] = trs[i].xpath('.//td')[6].text.replace('-0','-')
      if(record['date'] == '--'):
        continue # 公告后没有股权登记日,则跳过
      record['xd'] = round(float(trs[i].xpath('.//td')[3].text)/10.0, 2) # 分红
      record['xr'] = float(trs[i].xpath('.//td')[1].text)/10.0 # 送股
      record['xr'] += float(trs[i].xpath('.//td')[2].text)/10.0 # 转股
      record['xr'] = round(record['xr'], 2)
      result.append(record)
      if(isDebug):
        print('date:{date:10}, xd:{xd:6}, xr:{xr:6}'.format(**record))
  except:
    result = None
  return result
  
  
if __name__ == '__main__':
  code = '600004'
  isDebug = True
  GetStockBonus(code, isDebug)